package cn.baiweigang.uu.task;

import cn.baiweigang.uu.BTContext;
import cn.baiweigang.uu.api.linearswap.MarketWs;
import cn.baiweigang.uu.constants.BtcConfig;
import cn.baiweigang.uu.model.AccountInfo;
import cn.baiweigang.uu.service.linearswap.AccountService;
import cn.baiweigang.uu.utils.DateUtil;
import cn.baiweigang.uu.utils.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

@Configuration
@EnableScheduling
@EnableAsync
public class MarketWsTask {

    @Autowired
    private MarketWs marketWs;
    @Autowired
    private AccountService accountService;

    @Scheduled(cron = "0 0/15 * * * ?")
    private void sub() {
        LogUtil.logInfo("检查市场行情ws更新情况 上次更新时间=" +
                DateUtil.formatDateYMDHMS(new Date(BTContext.OrderPriceRefreshTs)));
        //10分钟没更新了，重新注册下
        if (DateUtil.getTs() - BTContext.OrderPriceRefreshTs > 10 * 60 * 1000) {
            LogUtil.logInfo("已10分钟未更新，重新订阅下");
            BTContext.OrderPriceRefreshTs = DateUtil.getTs();
            AccountInfo accountInfo = accountService.queryFromDb(BtcConfig.ACCOUNT_NAME);
            marketWs.setWsNull();
            marketWs.sub(accountInfo.getContractCode(), accountInfo.getPeriod());
        } else {
            LogUtil.logInfo("报价ws连接正常 无需重连");
        }
    }
}
